from flask import render_template, redirect, url_for, flash, request, jsonify, current_app, send_from_directory
from flask_login import login_required, current_user
from app.admin import bp
from app.models import User, Thesis, Permission, Role, Message
from app.decorators import admin_required
from app import db
from datetime import datetime
import os
from werkzeug.utils import secure_filename
from app.admin.forms import AdminThesisForm  # 导入管理员表单

@bp.route('/')
@login_required
@admin_required
def index():
    return render_template('admin/index.html', title='管理后台')

@bp.route('/users')
@login_required
@admin_required
def users():
    page = request.args.get('page', 1, type=int)
    pagination = User.query.order_by(User.created_at.desc())\
        .paginate(page=page, per_page=10, error_out=False)
    users = pagination.items
    return render_template('admin/users.html', users=users, pagination=pagination)

@bp.route('/user/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    if user.id == current_user.id:
        flash('不���删除自己的账号！')
        return redirect(url_for('admin.users'))
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除')
    return redirect(url_for('admin.users'))

@bp.route('/theses')
@login_required
@admin_required
def theses():
    page = request.args.get('page', 1, type=int)
    pagination = Thesis.query.order_by(Thesis.created_at.desc())\
        .paginate(page=page, per_page=10, error_out=False)
    theses = pagination.items
    return render_template('admin/theses.html', theses=theses, pagination=pagination)

@bp.route('/thesis/<int:id>/status', methods=['POST'])
@login_required
@admin_required
def update_thesis_status(id):
    thesis = Thesis.query.get_or_404(id)
    status = request.form.get('status')
    
    # 检查状态值是否有效
    if status not in ['pending', 'accepted', 'completed']:
        flash('无效的状态值')
        return redirect(url_for('admin.theses'))
    
    # 记录旧状态
    status_map = {
        'pending': '待处理',
        'accepted': '已接受',
        'completed': '已完成'
    }
    old_status = status_map.get(thesis.status, thesis.status)
    new_status = status_map.get(status, status)
    
    # 更新状态
    thesis.status = status
    
    # 创建通知消息
    message = Message(
        content=f'您的论��� "{thesis.title}" 状态已更新为"{new_status}"',
        user_id=thesis.user_id,
        thesis_id=thesis.id
    )
    
    try:
        db.session.add(message)
        db.session.commit()
        flash(f'论文状态已从"{old_status}"更新为"{new_status}"')
    except Exception as e:
        db.session.rollback()
        flash('状态更新失败')
        print(f"Error updating status: {e}")
    
    return redirect(url_for('admin.theses'))

@bp.route('/user/<int:id>/toggle_active', methods=['POST'])
@login_required
@admin_required
def toggle_user_active(id):
    user = User.query.get_or_404(id)
    user.is_active = not user.is_active
    db.session.commit()
    flash(f'用户 {user.username} 状态已更新')
    return redirect(url_for('admin.users'))

@bp.route('/thesis/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_thesis(id):
    thesis = Thesis.query.get_or_404(id)
    form = AdminThesisForm()
    if form.validate_on_submit():
        thesis.title = form.title.data
        thesis.description = form.description.data
        thesis.programming_language = form.programming_language.data
        thesis.price = form.price.data
        thesis.contact_info = form.contact_info.data
        thesis.deadline = form.deadline.data
        thesis.need_environment = form.need_environment.data
        thesis.status = form.status.data
        
        # 如果上传了新文件
        if form.proposal_file.data:
            # 删除旧文件
            if thesis.proposal_file:
                old_file = os.path.join(current_app.root_path, 'static', 'uploads', thesis.proposal_file)
                if os.path.exists(old_file):
                    os.remove(old_file)
            
            # 保存新文件
            f = form.proposal_file.data
            filename = secure_filename(f.filename)
            unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
            upload_dir = os.path.join(current_app.root_path, 'static', 'uploads')
            os.makedirs(upload_dir, exist_ok=True)
            file_path = os.path.join(upload_dir, unique_filename)
            f.save(file_path)
            thesis.proposal_file = unique_filename
        
        db.session.commit()
        flash('论文信息已更新')
        return redirect(url_for('admin.theses'))
        
    elif request.method == 'GET':
        form.title.data = thesis.title
        form.description.data = thesis.description
        form.programming_language.data = thesis.programming_language
        form.price.data = thesis.price
        form.contact_info.data = thesis.contact_info
        form.deadline.data = thesis.deadline
        form.need_environment.data = thesis.need_environment
        form.status.data = thesis.status
    
    return render_template('admin/edit_thesis.html', form=form, thesis=thesis)

@bp.route('/thesis/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_thesis(id):
    thesis = Thesis.query.get_or_404(id)
    if thesis.proposal_file:
        file_path = os.path.join(current_app.root_path, 'static', 'uploads', thesis.proposal_file)
        if os.path.exists(file_path):
            os.remove(file_path)
    db.session.delete(thesis)
    db.session.commit()
    flash('论文已删除')
    return redirect(url_for('admin.theses')) 